import json

from asgiref.sync import async_to_sync
from celery.result import AsyncResult
from channels.layers import get_channel_layer
from django.conf import settings
from websocket import create_connection

from celery_comsumer.config import WEBSOCKET_PATH
from celery_comsumer.main import app



@app.task
def triget_process(machine_code,path,rpa_type):

    runner = Runner(machine_code, path, rpa_type)
    res = runner.triger()

    return res





class Runner(object):
    def __init__(self,machine_code,path,rpa_type):
        self.machine_code = machine_code
        self.path = path.strip()
        self.rpa_type = rpa_type

    def send_socket(self,rpa_type,path):
        socket_url = "%sws/job/%s" %(WEBSOCKET_PATH,self.machine_code)
        print(socket_url)
        ws = create_connection(socket_url)
        msg_dict = {
            'rpa_type': rpa_type,
            'path': path
        }
        print(json.dumps(msg_dict))
        ws.send(json.dumps(msg_dict))
        result = ws.recv()
        ws.close()
        return "触发成功-url:{},data:{}".format(socket_url,json.dumps(msg_dict))


    def triger(self):
        pass
        print("触发triget")
        result = self.send_socket(self.rpa_type,self.path)

        return result
#


